<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://unpkg.com/axios@0.18.0/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
    <title>polling</title>
</head>
<body>
<div id="app">
    <button @click="longPolling">http 长轮询</button>
    <button @click="stopPolling">停止轮询</button>
    <p>{{time}}</p>
</div>
<script>
    window.onload=function(){
        let vm=new Vue({
            el:'#app',
            data:{
                time: '',
                timer: null
            },
            methods: {
                stopPolling() {
                    this.timer = null
                },
                longPolling() {
                    if(!this.timer){
                        this.timer = true
                        this.getTime()
                    }
                },
                getTime(){
                    window.axios.get('/longPolling', {timeout: 1000}).then(res => {
                        this.time = res.data
                        this.timer && this.getTime()
                    }).catch(err => {
                        console.log(err)
                        this.timer && this.getTime()
                    })
                }
            }
        });
    };
</script>
</body>
</html>
